/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.benmei.ntlive;
import com.benmei.ntlive.server.netty.SessionRepository;
import com.benmei.ntlive.server.netty.socket.TCPServer;
import com.benmei.ntlive.server.netty.socket.handler.NtliveChannelInitializer;
import com.benmei.ntlive.server.netty.websocket.WebSocketServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Spring Java Configuration and Bootstrap
 * Srping Boot and Netty的整合
 *
 * @author Peter
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception{
        // 启动Spring
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
//        //启动sslwebsocket,测试环境中使用
//        final SSLWebSocketServer wssServer=context.getBean(SSLWebSocketServer.class);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                wssServer.start();
//            }
//        }).start();

        //启动websocket Server
        final WebSocketServer wsServer=context.getBean(WebSocketServer.class);
        new Thread(new Runnable() {
            @Override
            public void run() {
                wsServer.start();
            }
        }).start();
        // 启动 Netty Tcp Server
        TCPServer tcpServer = context.getBean(TCPServer.class);
        tcpServer.start();
    }

    @Value("${websocket.port}")
    private int websocketPort;
//    测试
//    @Value("${SslWebSocket.port}")
//    private int sslWebSocketPort;

    @Value("${tcp.port}")
    private int tcpPort;

    @Value("${boss.thread.count}")
    private int bossCount;

    @Value("${worker.thread.count}")
    private int workerCount;

    @Value("${so.keepalive}")
    private boolean keepAlive;

    @Value("${so.backlog}")
    private int backlog;

    @SuppressWarnings("unchecked")
    @Bean(name = "serverBootstrap")
    public ServerBootstrap bootstrap() {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(somethingChannelInitializer);
        Map<ChannelOption<?>, Object> tcpChannelOptions = tcpChannelOptions();
        Set<ChannelOption<?>> keySet = tcpChannelOptions.keySet();
        for (@SuppressWarnings("rawtypes") ChannelOption option : keySet) {
            b.option(option, tcpChannelOptions.get(option));
        }
        return b;
    }

    @Autowired
    @Qualifier("ntliveChannelInitializer")
    private NtliveChannelInitializer somethingChannelInitializer;

    @Bean(name = "tcpChannelOptions")
    public Map<ChannelOption<?>, Object> tcpChannelOptions() {
        Map<ChannelOption<?>, Object> options = new HashMap<ChannelOption<?>, Object>();
        options.put(ChannelOption.SO_KEEPALIVE, keepAlive);
        options.put(ChannelOption.SO_BACKLOG, backlog);
        return options;
    }

    @Bean(name = "bossGroup", destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup(bossCount);
    }

    @Bean(name="websocketPort")
    public int websocketPort(){
        return websocketPort;
    }
// 测试环境
//    @Bean(name="sslWebSocketPort")
//    public int sslWebsocketPort(){
//        return sslWebSocketPort;
//    }

    @Bean(name = "workerGroup", destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup(workerCount);
    }

    @Bean(name = "tcpSocketAddress")
    public InetSocketAddress tcpPort() {
        return new InetSocketAddress(tcpPort);
    }

    @Bean(name = "sessionRepository")
    public SessionRepository channelRepository() {
        return new SessionRepository();
    }



}